"""This module send heartbeat to mongodb.
yangpan
"""

import logging
from time import time

import bigchaindb
from bigchaindb import Bigchain
import sched,time
import threading


logger = logging.getLogger(__name__)

schedule = sched.scheduler(time.time, time.sleep)

def updata(inc):
    try:
        bigchain = Bigchain()
        publickey = bigchaindb.config['keypair']['public']

        hostinfo = {}
        hostinfo['publickey'] = publickey
        hostinfo['time'] = time.time()

        schedule.enter(inc, 0, updata, (inc,))
        bigchain.update_hostinfo(hostinfo=hostinfo)

        nodes_except_me = bigchain.get_nodes_except_me()
        bigchaindb.config['keyring'] = nodes_except_me
    except:
        schedule.enter(inc, 0, updata, (inc,))

def while_update():
    schedule.enter(0, 0, updata, (10, ))
    schedule.run()

def do_while():
    t = threading.Thread(target=while_update())
    t.setDaemon(True)
    t.start()

def start():
    do_while()
